// ConfigManager.cpp
#include "ConfigManager.h"
#include <CommandParser.h>

ConfigManager::ConfigManager()
    : configLoaded(false), configCallback(nullptr), callbackUserData(nullptr)
{
    memset(&config, 0, sizeof(config));
}

ConfigManager::~ConfigManager()
{
    if (config.system.autoSave)
    {
        save();
    }
}

bool ConfigManager::begin()
{
    EEPROM.begin(CONFIG_EEPROM_SIZE);

    // 尝试加载配置
    if (!load())
    {
        DEBUG_PRINTLN("Failed to load config, setting defaults");
        setDefaultConfig();
        if (!save())
        {
            DEBUG_PRINTLN("Failed to save default config");
            return false;
        }
    }

    configLoaded = true;
    DEBUG_PRINTLN("ConfigManager initialized successfully");
    DEBUG_PRINTF("Config size: %u bytes\n", getConfigSize());
    DEBUG_PRINTF("Config version: 0x%08X\n", getConfigVersion());

    return true;
}

bool ConfigManager::save()
{
    if (!validateConfig())
    {
        DEBUG_PRINTLN("Config validation failed before save");
        return false;
    }

    config.magic = CONFIG_MAGIC;
    config.version = CONFIG_VERSION;

    // 计算CRC（不包括CRC字段本身）
    config.crc = 0;
    config.crc = calculateCRC((uint8_t *)&config, sizeof(ConfigData) - sizeof(uint32_t));

    // 写入EEPROM
    uint8_t *data = (uint8_t *)&config;
    for (size_t i = 0; i < sizeof(ConfigData); i++)
    {
        EEPROM.write(i, data[i]);
    }

    bool result = EEPROM.commit();

    if (result)
    {
        DEBUG_PRINTLN("Configuration saved successfully");
        notifyConfigChange("all");
    }
    else
    {
        DEBUG_PRINTLN("Failed to save configuration");
    }

    return result;
}

bool ConfigManager::load()
{
    ConfigData loadedConfig;
    uint8_t *data = (uint8_t *)&loadedConfig;

    // 从EEPROM读取
    for (size_t i = 0; i < sizeof(ConfigData); i++)
    {
        data[i] = EEPROM.read(i);
    }

    // 验证魔数
    if (loadedConfig.magic != CONFIG_MAGIC)
    {
        DEBUG_PRINTLN("Config magic number mismatch");
        return false;
    }

    // 验证CRC
    uint32_t storedCRC = loadedConfig.crc;
    loadedConfig.crc = 0;
    uint32_t calculatedCRC = calculateCRC(data, sizeof(ConfigData) - sizeof(uint32_t));

    if (storedCRC != calculatedCRC)
    {
        DEBUG_PRINTLN("Config CRC mismatch");
        return false;
    }

    // 验证配置版本
    if ((loadedConfig.version & 0xFFFF0000) != (CONFIG_VERSION & 0xFFFF0000))
    {
        DEBUG_PRINTLN("Config version incompatible");
        return false;
    }

    // 复制配置数据
    memcpy(&config, &loadedConfig, sizeof(ConfigData));

    // 硬件兼容性检查
    if (config.bt.classicEnabled && !CLASSIC_BT_SUPPORTED)
    {
        DEBUG_PRINTLN("Classic BT config found but not supported, disabling");
        config.bt.classicEnabled = false;
    }

    if (config.bt.bleEnabled && !BLE_SUPPORTED)
    {
        DEBUG_PRINTLN("BLE config found but not supported, disabling");
        config.bt.bleEnabled = false;
    }

    // 验证配置完整性
    if (!validateConfig())
    {
        DEBUG_PRINTLN("Loaded config validation failed");
        return false;
    }

    DEBUG_PRINTLN("Configuration loaded successfully");
    notifyConfigChange("all");
    return true;
}

bool ConfigManager::resetToDefaults()
{
    setDefaultConfig();
    bool result = save();
    if (result)
    {
        DEBUG_PRINTLN("Configuration reset to defaults");
    }
    return result;
}

// ConfigManager.cpp - 修复 setDefaultConfig 函数
void ConfigManager::setDefaultConfig()
{
    memset(&config, 0, sizeof(config));

    // 设置默认设备名
    String defaultName = "ESP32-Device";
#ifdef CHIP_NAME
    defaultName = String(CHIP_NAME) + "-" + String(ESP.getEfuseMac(), HEX);
#else
    defaultName = "ESP32-" + String(ESP.getEfuseMac(), HEX);
#endif

    // 默认WiFi配置
    setWiFiConfig("", "", false, true);

    // 默认蓝牙配置
    if (CLASSIC_BT_SUPPORTED && BLE_SUPPORTED)
    {
        setBluetoothConfig(defaultName.c_str(), true, false, true);
    }
    else if (BLE_SUPPORTED)
    {
        setBluetoothConfig(defaultName.c_str(), true, false, true);
    }
    else if (CLASSIC_BT_SUPPORTED)
    {
        setBluetoothConfig(defaultName.c_str(), false, true, true);
    }
    else
    {
        setBluetoothConfig(defaultName.c_str(), false, false, true);
    }

    // 默认网络配置
    setNetworkConfig(defaultName.c_str(), true);

    // 默认系统配置
    setSystemConfig(CMD_TIMEOUT_MS, CMD_BUFFER_SIZE, true, 1);

    // 确保默认锁定状态和密码
    config.system.locked = true;
    strncpy(config.system.unlockPassword, "123456", sizeof(config.system.unlockPassword) - 1);
    config.system.unlockPassword[sizeof(config.system.unlockPassword) - 1] = '\0';

    config.magic = CONFIG_MAGIC;
    config.version = CONFIG_VERSION;

    DEBUG_PRINTLN("[DEBUG] Default config set with password: " + String(config.system.unlockPassword));
}

bool ConfigManager::validateConfig()
{
    // 检查魔数
    if (config.magic != CONFIG_MAGIC)
    {
        DEBUG_PRINTLN("Config magic number invalid");
        return false;
    }

    // 检查版本兼容性
    if ((config.version & 0xFFFF0000) != (CONFIG_VERSION & 0xFFFF0000))
    {
        DEBUG_PRINTLN("Config version incompatible");
        return false;
    }

    // 检查WiFi配置
    if (strlen(config.wifi.ssid) > sizeof(config.wifi.ssid))
    {
        DEBUG_PRINTLN("WiFi SSID too long");
        return false;
    }

    // 检查蓝牙配置
    if (strlen(config.bt.deviceName) > sizeof(config.bt.deviceName))
    {
        DEBUG_PRINTLN("Bluetooth device name too long");
        return false;
    }

    // 检查网络配置
    if (strlen(config.network.hostname) > sizeof(config.network.hostname))
    {
        DEBUG_PRINTLN("Hostname too long");
        return false;
    }

    // 检查硬件兼容性
    if (config.bt.classicEnabled && !CLASSIC_BT_SUPPORTED)
    {
        DEBUG_PRINTLN("Classic BT enabled but not supported");
        return false;
    }

    if (config.bt.bleEnabled && !BLE_SUPPORTED)
    {
        DEBUG_PRINTLN("BLE enabled but not supported");
        return false;
    }

    return true;
}

uint32_t ConfigManager::calculateCRC(const uint8_t *data, size_t length)
{
    uint32_t crc = 0xFFFFFFFF;
    for (size_t i = 0; i < length; i++)
    {
        crc ^= data[i];
        for (int j = 0; j < 8; j++)
        {
            crc = (crc >> 1) ^ (0xEDB88320 & -(crc & 1));
        }
    }
    return ~crc;
}

void ConfigManager::setWiFiConfig(const char *ssid, const char *password, bool isAP, bool autoConnect)
{
    strncpy(config.wifi.ssid, ssid, sizeof(config.wifi.ssid) - 1);
    config.wifi.ssid[sizeof(config.wifi.ssid) - 1] = '\0';

    if (password)
    {
        strncpy(config.wifi.password, password, sizeof(config.wifi.password) - 1);
        config.wifi.password[sizeof(config.wifi.password) - 1] = '\0';
    }
    else
    {
        memset(config.wifi.password, 0, sizeof(config.wifi.password));
    }

    config.wifi.isAP = isAP;
    config.wifi.autoConnect = autoConnect;

    notifyConfigChange("wifi");
}

void ConfigManager::setBluetoothConfig(const char *deviceName, bool bleEnabled, bool classicEnabled, bool discoverable)
{
    strncpy(config.bt.deviceName, deviceName, sizeof(config.bt.deviceName) - 1);
    config.bt.deviceName[sizeof(config.bt.deviceName) - 1] = '\0';

    // 根据硬件支持调整配置
    config.bt.bleEnabled = bleEnabled && BLE_SUPPORTED;
    config.bt.classicEnabled = classicEnabled && CLASSIC_BT_SUPPORTED;
    config.bt.discoverable = discoverable;

    notifyConfigChange("bluetooth");
}

void ConfigManager::setBluetoothMode(bool bleEnabled, bool classicEnabled)
{
    config.bt.bleEnabled = bleEnabled && BLE_SUPPORTED;
    config.bt.classicEnabled = classicEnabled && CLASSIC_BT_SUPPORTED;
    notifyConfigChange("bluetooth");
}

void ConfigManager::setNetworkConfig(const char *hostname, bool dhcpEnabled)
{
    strncpy(config.network.hostname, hostname, sizeof(config.network.hostname) - 1);
    config.network.hostname[sizeof(config.network.hostname) - 1] = '\0';

    config.network.dhcpEnabled = dhcpEnabled;
    notifyConfigChange("network");
}

void ConfigManager::setStaticIP(const uint8_t ip[4], const uint8_t gateway[4],
                                const uint8_t subnet[4], const uint8_t dns[4])
{
    memcpy(config.network.staticIP, ip, 4);
    memcpy(config.network.gateway, gateway, 4);
    memcpy(config.network.subnet, subnet, 4);
    memcpy(config.network.dns, dns, 4);
    config.network.dhcpEnabled = false;
    notifyConfigChange("network");
}

void ConfigManager::setSystemConfig(uint32_t commandTimeout, uint16_t bufferSize,
                                    bool autoSave, uint8_t logLevel)
{
    config.system.commandTimeout = commandTimeout;
    config.system.bufferSize = min(bufferSize, (uint16_t)MAX_CMD_LENGTH);
    config.system.autoSave = autoSave;
    config.system.logLevel = min(logLevel, (uint8_t)3);
    notifyConfigChange("system");
}

void ConfigManager::printConfig()
{
    if (!configLoaded)
    {
        DEBUG_PRINTLN("Config not loaded");
        return;
    }

    DEBUG_PRINTLN("=== Current Configuration ===");

    // WiFi配置
    DEBUG_PRINTF("WiFi - SSID: %s, Mode: %s, AutoConnect: %s\n",
                 config.wifi.ssid,
                 config.wifi.isAP ? "AP" : "STA",
                 config.wifi.autoConnect ? "Yes" : "No");

    // 蓝牙配置
    DEBUG_PRINTF("Bluetooth - Name: %s, BLE: %s, Classic: %s\n",
                 config.bt.deviceName,
                 config.bt.bleEnabled ? "Yes" : "No",
                 config.bt.classicEnabled ? "Yes" : "No");

    // 网络配置
    DEBUG_PRINTF("Network - Hostname: %s, DHCP: %s\n",
                 config.network.hostname,
                 config.network.dhcpEnabled ? "Yes" : "No");

    // 系统配置
    DEBUG_PRINTF("System - Timeout: %lu ms, Buffer: %u bytes, AutoSave: %s\n",
                 config.system.commandTimeout,
                 config.system.bufferSize,
                 config.system.autoSave ? "Yes" : "No");

    DEBUG_PRINTLN("=============================");
}

void ConfigManager::setConfigChangeCallback(ConfigChangeCallback callback, void *userData)
{
    configCallback = callback;
    callbackUserData = userData;
}

void ConfigManager::notifyConfigChange(const char *section)
{
    if (configCallback)
    {
        configCallback(section, callbackUserData);
    }
}